//
//  emotionViewController.m
//  weibo3
//
//  Created by 吴天 on 11-5-21.
//  Copyright 2011年 nfsysu. All rights reserved.
//

#import "emotionViewController.h"
#import "RootViewController.h"
#import "NSEventExtras.h"
#import "Choices.h"


extern RootViewController *rootView;

#define KEY_NAME	@"name"
#define KEY_ICON	@"icon"
#define KEY_TAG		@"tag"

// NSNotification name to tell the Window controller to deal with collection view selection
NSString *HandleCollectionItem	= @"HandleCollectionItem";
NSString *SelectionIndexesContext = @"SelectionIndexesContext";


@implementation emotionViewBox

// -------------------------------------------------------------------------------
//	hitTest:aPoint
// -------------------------------------------------------------------------------
- (NSView *)hitTest:(NSPoint)aPoint
{
    // don't allow any mouse clicks for subviews in this NSBox
    return nil;
}

@end

@implementation emotionCollectionView


// -------------------------------------------------------------------------------
//	keyDown:theEvent
//
//	If the user hits enter/return on the collection view while tracking - perform the selection.
// -------------------------------------------------------------------------------
- (void)keyDown:(NSEvent *)theEvent
{
	if ([theEvent isReturnOrEnterKeyEvent])
	{
		NSIndexSet *selection = [self selectionIndexes];
		if ([selection count] > 0)
		{
			// dismiss the menu
			NSMenu *menu = [[self enclosingMenuItem] menu];
			[menu cancelTracking];  // this will cause a "NSMenuDidEndTrackingNotification" notification
		}
	}
	else
	{
		[super keyDown:theEvent];
	}
}

// -------------------------------------------------------------------------------
//	viewDidMoveToWindow
//
//	Make items in our view keyboard-navigable from the start.
// -------------------------------------------------------------------------------
- (void)viewDidMoveToWindow
{
	[super viewDidMoveToWindow];
	
	if (self.window)
	{
		[self.window makeFirstResponder:self];
	}
}

@end


@interface emotionViewController ()
- (void)gatherContents:(id)inObject;
@end
@implementation emotionViewController

@synthesize images;

// -------------------------------------------------------------------------------
//	handleEndTrack:notif
// -------------------------------------------------------------------------------
- (void)handleEndTrack:(NSNotification *)notif
{
    NSArray *selection = [arrayController selectedObjects];
	
	// clear the current selection for the next time
	[arrayController setSelectedObjects:nil];
    
	NSEvent *curEvent = [[NSApplication sharedApplication] currentEvent];
    if ([curEvent type] == NSKeyDown && [curEvent keyCode] == 53)	// check for escape-key
    {
		return;
	}
	else
	{
		// check if it's "our" menu
		NSMenu *menu = [notif object];
		if (menu != nil && menu == [[[self view] enclosingMenuItem] menu])
		{
			if (selection && [selection count] > 0)
			{
				// fetch the tag for the collection item, used to notify which item was chosen
				NSMutableDictionary *selectedItem = [selection objectAtIndex:0];
				NSString * name = [selectedItem valueForKey:KEY_NAME];
                
				// send this notification to the window controller to handle the selection
				[[NSNotificationCenter defaultCenter] postNotificationName:HandleCollectionItem object:name];
			}
		}
	}
}


- (NSMutableArray *)configArray:(NSMutableArray *) origiArray{
    NSMutableArray * doneArray = [[NSMutableArray alloc] init];
    
    
    for (int i = 0; i < [origiArray count]; i++) {
        NSDictionary * currentDic = [origiArray objectAtIndex:i];
        
        NSString * imageUrl = [currentDic valueForKey:@"url"];
        NSLog(@"imageUrl:\n%@",imageUrl);
        NSImage * tempImage = [[NSImage alloc] initWithContentsOfURL:[NSURL URLWithString:imageUrl]];
        NSString * tempName = [currentDic valueForKey:@"phrase"];
        
        [doneArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                             tempImage, KEY_ICON,
                             tempName, KEY_NAME,
                             [NSNumber numberWithInt:i], KEY_TAG,
                             nil]];
        
        [tempImage release];
        
    }
    
    return doneArray;
    
}

- (void)updateIcons:(id)obj
{
	self.images = obj;	// set this icon array to our collection
	
	// start out with no default selected item
	[arrayController setSelectionIndex:NSNotFound];
	
	// start listening for collection view selection changes through our array controller
	[arrayController addObserver:self
                          forKeyPath:@"selectionIndexes"
                             options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
                             context:SelectionIndexesContext];
}


- (void)gatherContents:(id)inObject{
    
    NSMutableArray *recivedArray = [[NSMutableArray alloc] 
                                    initWithArray:[rootView getEmotionsArrayWithCount:125]];
    
    NSMutableArray *contentArray = [self configArray:recivedArray];
    
    [self performSelectorOnMainThread:@selector(updateIcons:) withObject:contentArray waitUntilDone:NO];
	[recivedArray release];
    
}

/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    
    return self;
}
 */

// -------------------------------------------------------------------------------
//	awakeFromNib:
// -------------------------------------------------------------------------------
- (void)awakeFromNib
{
	// bind our collection view's contents and selection to our array controller
	
	[collectionView setFocusRingType:NSFocusRingTypeNone];	// we don't want a focus ring
	
	[collectionView setAllowsMultipleSelection:NO];	// as a menu we only allow one choice
	[collectionView setSelectable:YES];
	
	// start building our collection on a secondary thread in case it takes time
	[NSThread detachNewThreadSelector:@selector(gatherContents:) toTarget:self withObject:nil];
    
	// listen for end track event of our menu (the bottleneck for handling selections)
	[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleEndTrack:)
                                                 name:NSMenuDidEndTrackingNotification
                                               object:[[[self view] enclosingMenuItem] menu]];
	
	[arrayController setSelectedObjects:nil];	// clear the current selection for the next time
}


- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"selectionIndexes"];
	[images release];
	
	[super dealloc];

}

// -------------------------------------------------------------------------------
//	observeValueForKeyPath:ofObject:change:context
//
//	Listen for changes in the "selectionIndexes" of our array controller.
// -------------------------------------------------------------------------------
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object 
                        change:(NSDictionary *)change 
                       context:(void *)context
{
    if (context == SelectionIndexesContext)	// be sure this is the right notification for us
	{
		NSEvent *curEvent = [NSApp currentEvent];
		
        // don't act on the selection if the user is type-navigating or dragging the mouse
        if ([curEvent type] != NSKeyDown && [curEvent type] != NSLeftMouseDragged)
        {
            NSArray *selection = [object selectedObjects];
			if (selection && [selection count] > 0)
			{
				// dismiss the menu
				NSMenu *menu = [[[self view] enclosingMenuItem] menu];
				[menu cancelTracking];  // this will cause a "NSMenuDidEndTrackingNotification" notification
			}
		}
	}
	else
	{
		[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
	}
}


@end
